home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-04 / netprog.zip / NETPROG.TAR / rlogin / rresvport.c < prev   
C/C++ Source or Header  |  1989-12-17  |  2KB  |  69 lines

  1. /*
  2.  * Copyright (c) 1983 Regents of the University of California.
  3.  * All rights reserved.
  4.  *
  5.  * Redistribution and use in source and binary forms are permitted
  6.  * provided that the above copyright notice and this paragraph are
  7.  * duplicated in all such forms and that any documentation,
  8.  * advertising materials, and other materials related to such
  9.  * distribution and use acknowledge that the software was developed
  10.  * by the University of California, Berkeley.  The name of the
  11.  * University may not be used to endorse or promote products derived
  12.  * from this software without specific prior written permission.
  13.  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
  14.  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
  15.  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  16.  */
  17.  
  18. /*
  19.  * From the file: "@(#)rcmd.c   5.20 (Berkeley) 1/24/89";
  20.  */
  21.  
  22. /*
  23.  * Obtain a reserved TCP port.
  24.  *
  25.  * Note that we only create the socket and bind a local reserved port
  26.  * to it.  It is the caller's responsibility to then connect the socket.
  27.  */
  28.  
  29. #include    <sys/types.h>
  30. #include    <sys/socket.h>
  31. #include    <netinet/in.h>
  32. #include    <errno.h>
  33. extern int    errno;
  34.  
  35. int            /* return socket descriptor, or -1 on error */
  36. rresvport(alport)
  37. int    *alport;    /* value-result; on entry = first port# to try */
  38.             /* on return = actual port# we were able to bind */
  39. {
  40.     struct sockaddr_in    my_addr;
  41.     int            sockfd;
  42.  
  43.     bzero((char *) &my_addr, sizeof(my_addr));
  44.     my_addr.sin_family      = AF_INET;
  45.     my_addr.sin_addr.s_addr = INADDR_ANY;
  46.  
  47.     if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  48.         return(-1);
  49.  
  50.     for ( ; ; ) {
  51.         my_addr.sin_port = htons((u_short) *alport);
  52.         if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof(my_addr)) >= 0)
  53.             break;        /* OK, all done */
  54.  
  55.         if (errno != EADDRINUSE) {    /* some other error */
  56.             close(sockfd);
  57.             return(-1);
  58.         }
  59.  
  60.         (*alport)--;    /* port already in use, try the next one */
  61.         if (*alport == IPPORT_RESERVED / 2) {
  62.             close(sockfd);
  63.             errno = EAGAIN;
  64.             return(-1);
  65.         }
  66.     }
  67.     return(sockfd);
  68. }
  69.